<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>axios基本使用</title>
</head>
<body>
    <div class="container">
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
    </div>

    <script>
        const btns = document.querySelectorAll('button');
        

        // GET请求: 获取id为2的文章
        btns[0].addEventListener('click',function() {
            // 发送ajax请求
            axios({
                method: 'GET',
                url: 'http://localhost:53000/posts/2',
            }).then(response => {
                console.log(response.data);
            });
        });

        // POST请求：添加一篇新的文章
        btns[1].addEventListener('click',function() {
            axios({
                method: 'POST',
                url: 'http://localhost:53000/posts',
                data: {
                    title: '今天天气风和日丽',
                    author: 'Katrina',
                },
            })
        });

        // PUT请求：更新数据
        btns[2].addEventListener('click',function() {
            axios({
                method: 'PUT',
                url: 'http://localhost:53000/posts/6',
                data: {
                    title: '今天天气风和日丽，天气真不错',
                    author: 'Katrinasayhello',
                }
            })
        });

        // DELETE请求：删除数据
        btns[3].addEventListener('click',function() {
            // 发送ajax请求
            axios({
                method: 'DELETE',
                url: 'http://localhost:53000/posts/4',
            });
        });
    </script>
</body>
</html>